# encoding: utf-8
class Admin::WatchingsController < AdminController

  set_tab :statistics
  set_tab :watching, :sub_nav
  before_filter :setup, only: [:index]

  def index
    params[:watching] ||= {}
    @watching = Watching
    @watching = @watching.includes(:client).by_client(params[:watching][:client_id]) unless params[:watching][:client_id].blank?
    @watching = @watching.includes(:account).by_account(params[:watching][:account_id]) unless params[:watching][:account_id].blank?
    @watching = @watching.before_date(params[:watching][:end_date]) unless params[:watching][:end_date].blank?
    @watching = @watching.after_date(params[:watching][:start_date]) unless params[:watching][:start_date].blank?
    
    respond_to do |format|
      format.html {
        @watching = @watching.page params[:page]
      }
      format.csv {   
        @watching = @watching.all
        send_data(csv_content_for(@watching),  
                  :type => "text/csv;charset=utf-8; header=present",  
                  :filename => "观看时长统计_#{Time.now.strftime("%Y%m%d")}.csv")  
      }
    end
  end

  private

  def setup
    @ways = ["统计","观看统计"]
    @left_panel = "layouts/statistics_left_panel"
  end

  def csv_content_for(objs)  
    CSV.generate do |csv|  
      csv << ["\xEF\xBB\xBF节目名称", "终端mac", "SID", "观看时长（S）", "创建时间"]  
      objs.each do |watching|  
        csv << [  
          watching.television_name,  
          watching.client.try(:mac),
          watching.sid,
          watching.seconds,
          watching.created_at.stamp("2013-03-12 22:02:01")
        ]
      end
    end
  end

end